#Table A9

#directory
#set working directory to the path PvP_Replication
#setwd("~/PvP_Replication")

#packages
library(tidyverse) #for data cleaning and manipulation
library(sensemakr) # sensitivity analyses
library(estimatr) #estimation

#load main dataset
pvp_data <- read.csv("PvP_data/PvP_data_main.csv")

#transform independent variable
#create log + 1 cultivation variable
pvp_data <- pvp_data %>% 
  mutate(logcult = log(maxcult + 1))

#subset data to municipalities with prior FARC presence
pvp_farc_subset <- pvp_data %>% filter(farc_presence == 1)

#prep weather and soil variables for iv
pvp_farc_subset <- pvp_farc_subset %>% mutate(
  draindummy = as.factor(ifelse(DRAIN == "M", 1, 0)), #moderate drainage
  humiddist = case_when(humid_mean < 85 ~ (85 - humid_mean)^2, humid_mean > 85 ~ (humid_mean - 85)^2, TRUE ~ 0 ), #distance from optimal humidity point
  temprangedist = case_when(maxtemp > 27 ~ (maxtemp - 27)^2, mintemp < 14  ~ (14 - mintemp)^2, TRUE ~ 0), #distance from optimal temp, wide band
)

#instrument for continuous independent variable
pvp_farc_subset$ols_inst <- predict(lm(logcult ~ PHAQ + temprangedist + TOTN + TOTC + sun_mean + humiddist + raintot_me + draindummy, pvp_farc_subset))

#save reduced form model for continuous instrument on outcome
cult_iv_rf_ols <- lm_robust(dissident_presence ~ ols_inst, data = pvp_farc_subset)

#run sensmakr on reduced form model
iv_rf_sensitivity <- sensemakr(estimate = cult_iv_rf_ols$coefficients["ols_inst"], 
                                se = cult_iv_rf_ols$std.error["ols_inst"], 
                                dof = cult_iv_rf_ols$df["ols_inst"], 
                                treatment = "ols_inst",
                                )

#produce latex table for results
ovb_minimal_reporting(iv_rf_sensitivity)

#note that names of variables have to be changed manually: 
#outcome label is "FARC splinter group presence (binary)"
#instrument label is "weather and soil instrument"

